package com.example.demo.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.test",sqlSessionTemplateRef = "testSqlSessionTemplate")
public class DataSourceTestConfig {
    /**
     * 生成数据源，@Primary注解声明为默认数据源
     */
    @Bean(name="testDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test")
    public DataSource testDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建 SqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name="testSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource")DataSource dataSource)throws Exception{
        //SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //将sqlSession 替换成 MybatisSqlSession
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置事务管理
     * @param dataSource
     * @return
     */
    @Bean(name = "testTransaction")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("testDataSource")DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean(name="testSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
        throws Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
